package cb.com.etcdemo;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;


import com.github.czy1121.view.RoundButton;
import com.kaopiz.kprogresshud.KProgressHUD;

import cb.com.etcdemo.API.API;
import cb.com.etcdemo.bean.Login;
import cb.com.etcdemo.http.Okhttp;
import cb.com.etcdemo.util.JSONUtils;
import cb.com.etcdemo.util.SpfUtils;
import cb.com.etcdemohgz.R;


/**
 * 登录页面
 */
public class Signin_Activity extends FragmentActivity implements View.OnClickListener {


    private EditText et_mobile;
    private EditText et_password;
    private ImageView iv_clean_phone;
    private ImageView clean_password;
    private ImageView iv_show_pwd;
    private RoundButton btn_login;

    private int screenHeight = 0;//屏幕高度
    private int keyHeight = 0; //软件盘弹起后所占高度
    private float scale = 0.6f; //logo缩放比例
    private View service;
    private int height = 0;

    InputMethodManager imm;

    TextView forget_password;


    ImageView imageView;

    TextView textView20;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //设置输入法不弹起
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.activity_login2);
        AndroidBug5497Workaround.assistActivity(this);
        imageView = (ImageView) findViewById(R.id.imageView);
        textView20 = (TextView) findViewById(R.id.textView20);
//        textView20.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                startActivity(new Intent(Signin_Activity.this, ZhuCe_Activity.class));
//            }
//        });

        Rect outRect = new Rect();
        getWindow().getDecorView().getWindowVisibleDisplayFrame(outRect);
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) imageView.getLayoutParams();
        params.height = outRect.bottom - outRect.top;
        imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);


        intiView();
        initListener();

    }

//    SimpleTarget<Drawable> simpleTarget = new SimpleTarget<Drawable>() {
//        @Override
//        public void onResourceReady(Drawable resource, Transition<? super Drawable> transition) {
////            rela.setBackground(resource);
//        }
//    };


    private void intiView() {
        String LoginBackImagesss = (String) SpfUtils.get(Signin_Activity.this, "LoginBackImages", "");
        String o = (String) SpfUtils.get(Signin_Activity.this, "ImageUrl", "");


//        Glide.with(this).load(LoginBackImagesss).into(simpleTarget);

//        if (!TextUtils.isEmpty(o)) {
//            Glide.with(Signin_Activity.this).load(o).into(logo);
//        }


        et_mobile = (EditText) findViewById(R.id.et_mobile);

        et_password = (EditText) findViewById(R.id.et_password);
//        String name = (String) SPUtils.get(Signin_Activity.this, "UserName", "");
//        et_mobile.setText( name);
//        et_password.setText("test");
        iv_clean_phone = (ImageView) findViewById(R.id.iv_clean_phone);
        clean_password = (ImageView) findViewById(R.id.clean_password);
        iv_show_pwd = (ImageView) findViewById(R.id.iv_show_pwd);
        btn_login = (RoundButton) findViewById(R.id.btn_login);

//        forget_password.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                startActivity(new Intent(Signin_Activity.this, ReviseNumber_Activity.class));
//            }
//        });
//        TextView register = (TextView) findViewById(R.id.register);
//        register.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                startActivity(new Intent(Signin_Activity.this, Register_Activity.class));
//            }
//        });

//        service = findViewById(R.id.service);

        screenHeight = this.getResources().getDisplayMetrics().heightPixels; //获取屏幕高度
        keyHeight = screenHeight / 3;//弹起高度为屏幕高度的1/3
    }

    private void initListener() {
        iv_clean_phone.setOnClickListener(this);
        clean_password.setOnClickListener(this);
        iv_show_pwd.setOnClickListener(this);
        btn_login.setOnClickListener(this);

        et_password.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!TextUtils.isEmpty(s) && clean_password.getVisibility() == View.GONE) {
                    clean_password.setVisibility(View.VISIBLE);
                } else if (TextUtils.isEmpty(s)) {
                    clean_password.setVisibility(View.GONE);
                }
                if (s.toString().isEmpty())
                    return;
                if (!s.toString().matches("[A-Za-z0-9]+")) {
                    String temp = s.toString();
                    Toast.makeText(Signin_Activity.this, "请输入数字或字母", Toast.LENGTH_SHORT).show();
                    s.delete(temp.length() - 1, temp.length());
                    et_password.setSelection(s.length());
                }
            }
        });
//        scrollView.setOnTouchListener(new View.OnTouchListener() {
//            @Override
//            public boolean onTouch(View v, MotionEvent event) {
//                return true;
//            }
//        });
//        findViewById(R.id.root).addOnLayoutChangeListener(new ViewGroup.OnLayoutChangeListener() {
//            @Override
//            public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
//              /* old是改变前的左上右下坐标点值，没有old的是改变后的左上右下坐标点值
//              现在认为只要控件将Activity向上推的高度超过了1/3屏幕高，就认为软键盘弹起*/
//                if (oldBottom != 0 && bottom != 0 && (oldBottom - bottom > keyHeight)) {
//                    Log.e("wenzhihao", "up------>" + (oldBottom - bottom));
//                    new Handler().postDelayed(new Runnable() {
//                        @Override
//                        public void run() {
//                            scrollView.smoothScrollTo(0, scrollView.getHeight());
//                        }
//                    }, 0);
//
//                    service.setVisibility(View.INVISIBLE);
//                } else if (oldBottom != 0 && bottom != 0 && (bottom - oldBottom > keyHeight)) {
//                    Log.e("wenzhihao", "down------>" + (bottom - oldBottom));
//                    //键盘收回后，logo恢复原来大小，位置同样回到初始位置
//                    new Handler().postDelayed(new Runnable() {
//                        @Override
//                        public void run() {
//                            scrollView.smoothScrollTo(0, scrollView.getHeight());
//                        }
//                    }, 0);
//
//                    service.setVisibility(View.VISIBLE);
//                }
//            }
//        });
    }

    /**
     * 缩小
     *
     * @param view
     */
    public void zoomIn(final View view, float dist) {
        view.setPivotY(view.getHeight());
        view.setPivotX(view.getWidth() / 2);
        AnimatorSet mAnimatorSet = new AnimatorSet();
        ObjectAnimator mAnimatorScaleX = ObjectAnimator.ofFloat(view, "scaleX", 1.0f, scale);
        ObjectAnimator mAnimatorScaleY = ObjectAnimator.ofFloat(view, "scaleY", 1.0f, scale);
        ObjectAnimator mAnimatorTranslateY = ObjectAnimator.ofFloat(view, "translationY", 0.0f, -dist);

        mAnimatorSet.play(mAnimatorTranslateY).with(mAnimatorScaleX);
        mAnimatorSet.play(mAnimatorScaleX).with(mAnimatorScaleY);
        mAnimatorSet.setDuration(200);
        mAnimatorSet.start();
    }

    /**
     * f放大
     *
     * @param view
     */
    public void zoomOut(final View view, float dist) {
        view.setPivotY(view.getHeight());
        view.setPivotX(view.getWidth() / 2);
        AnimatorSet mAnimatorSet = new AnimatorSet();

        ObjectAnimator mAnimatorScaleX = ObjectAnimator.ofFloat(view, "scaleX", scale, 1.0f);
        ObjectAnimator mAnimatorScaleY = ObjectAnimator.ofFloat(view, "scaleY", scale, 1.0f);
        ObjectAnimator mAnimatorTranslateY = ObjectAnimator.ofFloat(view, "translationY", view.getTranslationY(), 0);

        mAnimatorSet.play(mAnimatorTranslateY).with(mAnimatorScaleX);
        mAnimatorSet.play(mAnimatorScaleX).with(mAnimatorScaleY);
        mAnimatorSet.setDuration(200);
        mAnimatorSet.start();
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.iv_clean_phone:
                et_mobile.setText("");
                break;

            case R.id.clean_password:
                et_password.setText("");
                break;
            case R.id.iv_show_pwd:
                if (et_password.getInputType() != InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD) {
                    et_password.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                    iv_show_pwd.setImageResource(R.drawable.pass_visuable);
                } else {
                    et_password.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                    iv_show_pwd.setImageResource(R.drawable.pass_gone);
                }
                String pwd = et_password.getText().toString();
                if (!TextUtils.isEmpty(pwd))
                    et_password.setSelection(pwd.length());
                break;
            case R.id.btn_login:

                if (TextUtils.isEmpty(et_mobile.getText().toString())) {
                    Toast.makeText(this, "请输入账号", Toast.LENGTH_SHORT).show();
                    return;
                } else if (TextUtils.isEmpty(et_password.getText().toString())) {
                    Toast.makeText(this, "请密码", Toast.LENGTH_SHORT).show();
                    return;
                }
                imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);


                YW_SIGN();


                break;


        }
    }

    KProgressHUD dialog;

    public void showdialog() {
        dialog = KProgressHUD.create(Signin_Activity.this)
                .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
                .setLabel("正在登录中，请稍候")
                .setCancellable(true)
                .setAnimationSpeed(2)
                .setDimAmount(0.5f)
                .show();
    }

    public void YW_SIGN() {
        showdialog();
        API.Login(et_mobile.getText().toString(), et_password.getText().toString(), new Okhttp.Objectcallback() {
            @Override
            public void onsuccess(String st) {
//                if (ALL_CONFIG.Debug) {
                Log.e("711login", st);
//                }
                if (dialog != null) {
                    dialog.dismiss();
                }

                Login sign_bean = JSONUtils.parseJSON(st, Login.class);
                if (sign_bean.getCode().equals("0")) {
                    Toast.makeText(Signin_Activity.this, "登录成功！", Toast.LENGTH_SHORT).show();
//                    SpfUtils.put(Signin_Activity.this, "islogin", true);
                    SpfUtils.put(Signin_Activity.this, "name", ""+sign_bean.getData().getName());
                    SpfUtils.put(Signin_Activity.this, "username",  sign_bean.getData().getUsername());
                    startActivity(new Intent(Signin_Activity.this, ResourceActivity.class));
                    finish();
                } else {
                    Toast.makeText(Signin_Activity.this,""+ sign_bean.getMsg(), Toast.LENGTH_SHORT).show();
                }

            }

            @Override
            public void onFalia(int code, String errst) {
//                if (ALL_CONFIG.Debug) {
                Log.e("711login", errst);
//                }
                if (dialog != null) {
                    dialog.dismiss();
                }
                Toast.makeText(Signin_Activity.this, "网络错误!", Toast.LENGTH_SHORT).show();


            }
        });

    }


}

